const user = require('../methods/user')
const vcode = require('../methods/vcode')
const tool = require('../tools/tool')
const settings = require('../methods/settings')
const permissions = require('../methods/permissions')
const runner = require('../runner')



module.exports = {
    login: {
        exp: '自动登录和注册',
        method: 'post',
        async func(data) {
            let openId = await user.getOpenId(data.param.code)
            if (!openId) throw '无法获取OpenId'
            let userInfo = await user.getSingleUserInfoByOpenId(openId)
            if (userInfo) {
                if (userInfo.isDisabled === 1) throw '账号被封禁'
                if (userInfo.isDisabled === 2) throw '尚未通过审核'
                let newToken = await user.genToken(openId, userInfo.id)
                await user.updateToken(userInfo.id, newToken)
                runner.currentData.logined = true
                userInfo = await user.getSingleUserInfoByOpenId(openId)
                //登录成功
                tool.cLog.userLogin(userInfo)
                return userInfo
            } else {
                if (data.param.userInfo !== undefined) {
                    if (!(await settings.getItem('allowReg'))) throw '不允许注册'
                    if (!vcode.check(data.param.userInfo.vcode, data.param.userInfo.phone)) throw '验证码不正确或已失效'
                    let id = await user.addNew(openId, data.param.userInfo)
                    if (await settings.getItem('accountVer')) {
                        await user.setUnlogin(id)
                        return {
                            disabled: true,
                            content: '注册成功，等待管理员审核'
                        }
                    }
                    await user.updateToken(id, await user.genToken(openId, id))
                    return {
                        disabled: false,
                        content: '注册成功'
                    }
                }
            }
            throw '无法自动登录'
        }
    },
    home: {
        exp: '获取主页上显示的内容',
        method: 'get',
        async func(data) {
            return {
                newPatrolDefaultWorkDays: await settings.getItem('newPatrolDefaultWorkDays'),
                maxDelayTime: await settings.getItem('maxDelayTime'),
                accountVer: await settings.getItem('accountVer'),
                allowReg: await settings.getItem('allowReg'),
                progress_feedBack: await settings.getItem('progress_feedBack'),
                progress_review: await settings.getItem('progress_review'),
                newPatrolSendNotificationWaitTime: await settings.getItem('newPatrolSendNotificationWaitTime'),
                sendMessage: await settings.getItem('sendMessage'),
                postWeChatMessage: await settings.getItem('postWeChatMessage'),
                dailyPatrolLimitPerUser: await settings.getItem('dailyPatrolLimitPerUser'),
                logFrontStatus: await settings.getItem('logFrontStatus'),
            }
        }
    },
    setOpenId: {
        exp: '设置OpenId（手动登录）',
        method: 'post',
        async func(data) {
            let openId = await user.getOpenId(data.param.code)
            if (data.param.loginType == 0) {
                let userInfo = await user.getSingleUserInfoByAccount(data.param.form.account)
                if (!userInfo) throw '用户不存在'
                if (userInfo.isDisabled === 1) throw '账号已封禁'
                if (userInfo.isDisabled === 2) throw '还没有通过审核'
                await user.checkUserPassword(data)
                await user.setOpenIdByAccount(data.param.form.account, openId)
            } else {
                let userInfo = await user.getSingleUserInfoByPhone(data.param.form.phone)
                if (!userInfo) throw '用户不存在'
                if (userInfo.isDisabled === 1) throw '账号已封禁'
                if (userInfo.isDisabled === 2) throw '还没有通过审核'
                if (!vcode.check(data.param.form.vcode, data.param.form.phone)) throw '验证码错误或已失效'
                await user.setOpenIdByPhone(data.param.form.phone, openId)
            }
        }
    },
    getDepartmentList: {
        exp: '获取用户角色表',
        method: 'get',
        async func(data) {
            return await user.getDepartmentList()
        }
    },
    getVCode: {
        exp: '获取验证码',
        method: 'get',
        async func(data) {
            let re = await vcode.get(data.query.phone)
            tool.sendMessage(data.query.phone, `您好，您的验证码为${re}，10分钟内有效。`)
        }
    },
    getOpenId: {
        exp: '获取OpenId',
        method: 'get',
        async func(data) {
            return await user.getOpenId(data.query.code)
        }
    },
    updateInfo: {
        exp: '更新用户信息',
        method: 'post',
        auth: true,
        async func(data) {
            let key = Object.keys(data.param)[0]
            if (!key) throw '没有指明Key'
            let value = data.param[Object.keys(data.param)[0]]
            switch (key) {
                case 'account':
                    await user.update.account(data.currentUserId, value)
                    break;
                case 'phone':
                    await user.update.phone(data.currentUserId, data.param.vcode, value)
                    break;
                default:
                    await user.updateInfo(data.currentUserId, data.param)
                    break;
            }
        }
    },
    exitLogin: {
        exp: '退出登录',
        method: 'post',
        auth: true,
        async func(data) {
            await user.exitLogin(data.currentUserId)
        }
    },
    myTasks: {
        exp: '我的事务',
        method: 'get',
        auth: true,
        async func(data) {
            // tool.cachef().reset('patrols')
            return await user.getMyTasks(data.currentUserId)
        }
    },
    permissions: {
        add: {
            exp: '添加权限',
            method: 'post',
            auth: {
                admin: true
            },
            async func(data) {
                await permissions.add(
                    data.param.userId,
                    data.param.type,
                    data.param.campusId,
                    data.param.categoryId
                )
            }
        },
        delete: {
            exp: '删除权限',
            method: 'post',
            auth: {
                admin: true
            },
            async func(data) {
                await permissions.delete(data.param.perId)
            }
        },
    },
    userData: {
        exp: '获取用户信息',
        auth: true,
        method: 'get',
        async func(data) {
            return await tool.methods.user().getSingleUserInfoByUserId(data.currentUserId)
        }
    },
    export: {
        exp: '导出用户',
        method: 'get',
        auth: {
            admin: true
        },
        async func(data) {
            user.admin.exportToExcel(data.currentUserId)
        }
    }
}